using System;
using System.Collections.Generic;

namespace OpenRay
{
	public class PinholeCamera : Camera
	{
		protected readonly float imagePlaneDistance, imageX, imageY;
		
		public PinholeCamera (IScene s, int x, int y, float imagePlaneDistance, float imagePlaneX, float imagePlaneY)
			: base( s, x, y )
		{
			this.imagePlaneDistance = imagePlaneDistance;
			this.imageX = imagePlaneX;
			this.imageY = imagePlaneY;
		}
		
		public override FrameBuffer Render()
		{
			Point LensLocation = new Point(0f, 0f, 0f);
			Point imagePlane = new Point( -imageX / 2f, -imageY / 2f, imagePlaneDistance );
			
			Vector dx = new Vector( imageX, 0f, 0f ) * (1.0f / (float)frame.Width);
			Vector dy = new Vector( 0f, imageY, 0f) * (1.0f / (float)frame.Width);
			
			for ( int y = 0; y < frame.Height; y++ )
			{
				for( int x = 0; x < frame.Width; x++ )
				{
					Point origin = imagePlane + dx * ((float)x + 0.5f) + dy * ((float)y + 0.5f);
					Ray r = new Ray(LensLocation, LensLocation - origin);
					
					IList<PrimitiveHit> hits = scene.Trace(r, maxDepth);
					
					if ( hits.Count > 0 )
					{
						frame.SetPixelArgb( frame.Width - 1 - x, y, hits[0].Shade(r).ToArgb() );
					}
				}
			}
			
			return frame;
		}
	}
}

